<template>
  <div v-click-outside="handleClickOutside">
    <div @click="handleToggle">
      <i-input
        v-model="keyword"
        :icon="currentBranch ? 'ios-close-empty' : ''"
        @on-change="handleRemoteSearch"
        @on-click.stop="handleClean"
        @keydown.native.up="handleOpen"
        @keydown.native.down="handleOpen"
        placeholder="输入门店名称搜索">
      </i-input>
    </div>
    <transition name="transition-drop">
      <Dropdown
        style="display:block"
        trigger="custom"
        placement="bottom-start"
        :visible="dropVisible"
        @on-click="handleSelect"
        @on-visible-change="handleVisibleChange">
        <DropdownMenu slot="list">
          <div class="dd-selector__wrap">
            <Spin v-if="loadingData" fix></Spin>
            <DropdownItem :name="0" :selected="0 === value" v-if="showHead && matchHead && pagination.current === 1">
              总部
            </DropdownItem>
            <DropdownItem v-for="item in list" :key="item.id" :name="item.id" :selected="item.id === value">
              {{item.name}}
            </DropdownItem>
            <div class="dd-selector__desc" v-show="noResult">
              <Icon type="information-circled" color="#008bea"></Icon> 无匹配数据
            </div>
          </div>

          <div class="dd-selector__container dd-selector__page">
            <Page
              simple
              style="margin:0"
              :total="pagination.total"
              :current.sync="pagination.current"
              :page-size="pagination.limit"
              @on-change="search"
            />
          </div>
        </DropdownMenu>
      </Dropdown>
    </transition>
  </div>
</template>
<script>
  import debounce from 'lodash/debounce'
  import { http, api } from '@/libs/http'
  import ClickOutside from 'vue-click-outside'

  export default {
    name: 'branch-selector',
    directives: {
      ClickOutside
    },
    props: {
      value: [String, Number],
      showHead: [Boolean, String]
    },
    data () {
      return {
        searchId: 0,
        loadingData: false,
        keyword: '',
        pagination: {
          current: 1,
          total: 0,
          limit: 10
        },
        dropVisible: false,
        list: [],
        currentBranch: null,
        noResult: false
      }
    },
    computed: {
      matchHead () {
        return !this.keyword || (
          ('总部'.includes(this.keyword))
        )
      }
    },
    watch: {
      currentBranch (n, o) {
        const value = n && n.id !== undefined ? n.id : ''
        const oldValue = o && o.id !== undefined ? o.id : ''
        if (value === oldValue) return
        this.$emit('input', value)
        this.$emit('on-change', value)
      }
    },
    methods: {
      handleOpen () {
        this.dropVisible = true
      },
      handleClickOutside: debounce(function () {
        if (this.dropVisible) this.dropVisible = false
        if (!this.currentBranch) this.keyword = ''
      }, 150),
      handleVisibleChange (visible) {
        if (visible) {
          if (!this.currentBranch) this.search()
        } else {
          setTimeout(() => {
            this.loadingData = false
            if (this.currentBranch) {
              this.keyword = this.currentBranch.name
            } else {
              this.list = []
              this.pagination.current = 1
              this.pagination.total = 0
            }
          }, 200)
        }
      },
      handleToggle () {
        this.dropVisible = !this.dropVisible
      },
      handleClean () {
        this.currentBranch = null
        this.keyword = ''
        this.dropVisible = false
      },
      handleSelect (branchId) {
        this.dropVisible = false
        if (branchId === 0) {
          this.currentBranch = { id: 0, name: '总部' }
        } else {
          const branch = this.list.find(item => item.id === branchId)
          if (!branch) return
          this.currentBranch = branch
        }
        this.keyword = (this.currentBranch && this.currentBranch.name) || ''
      },
      handleRemoteSearch: debounce(function () {
        if (!this.dropVisible) this.dropVisible = true
        const { keyword } = this
        if (this.currentBranch && this.currentBranch.name === keyword) return
        this.pagination.page = 1
        this.pagination.total = 0
        this.search()
      }, 200),
      async search () {
        try {
          this.searchId += 1
          const id = this.searchId
          this.loadingData = true
          this.noResult = false
          this.list = []
          const { keyword, pagination: { current, limit } } = this
          const query = { limit, offset: (current - 1) * limit }
          if (keyword) query.keyword = keyword
          const res = await http.req(api.branch_list, null, query)
          if (id !== this.searchId) return
          if (res) {
            const { count, list } = res
            this.list = list
            this.pagination.total = count
            if ((!list || list.length === 0) && !this.matchHead) this.noResult = true
          }
        } catch (err) {
          console.log(err)
        } finally {
          this.loadingData = false
        }
      }
    }
  }
</script>

<style lang="less">
  @import './selector.less';
</style>

